package nl.grol.yakshop.web.servlet;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.grol.yakshop.util.ConversionUtil;
import nl.grol.yakshop.util.InvalidInputException;

import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;

@SuppressWarnings("serial")
public abstract class BaseJsonServlet extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(BaseJsonServlet.class.getName());
	
	protected Integer extractLastPathSegmentFromRequest( HttpServletRequest req ) throws InvalidInputException {
		
		Iterable<String> parts = Splitter.on('/')
					       .trimResults()
					       .omitEmptyStrings()
					       .split(req.getRequestURI());
		String last = Iterables.getLast(parts);
		

		Integer id =  ConversionUtil.stringToNonNegativeInt(last);
		LOGGER.info( "Extracted " + id + "  from " + req.getRequestURI() + " with last:" + last );
		
		return id;
	}
	
	protected void writeSuccessResponse( HttpServletRequest req, HttpServletResponse resp, int statusCode ) throws IOException {
		/*
		 * return ok response
		 */
		LOGGER.info("Action \"" + req.getRequestURI() + "\" completed successfully with status " + statusCode);
		resp.setStatus(statusCode);
	}

	protected void writeSuccessResponse( HttpServletRequest req, HttpServletResponse resp, int statusCode, String data ) throws IOException {
		/*
		 * return ok response
		 */
		LOGGER.info("Action \"" + req.getRequestURI() + "\" completed successfully with status " + statusCode);
		resp.setStatus(statusCode);
		resp.setContentType("application/json");
		resp.setCharacterEncoding("utf-8");
		// TODO specify caching behaviour???
		resp.getWriter().print(data);
	}

	protected void writeErrorResponse( HttpServletRequest req, HttpServletResponse resp, int statusCode, Exception exc  )  throws IOException  {
		
		LOGGER.warning("Action \"" + req.getRequestURI() + "\" failed with status " + statusCode + ":" + exc.getMessage() );
		// report  error
		resp.setStatus(statusCode);
		//exc.printStackTrace(resp.getWriter());
	}

}
